package com.example.tutorial.reminder;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;

import com.example.tutorial.model.DaoMaster;
import com.example.tutorial.model.DaoMaster.DevOpenHelper;
import com.example.tutorial.model.DaoSession;
import com.example.tutorial.model.Task;
import com.example.tutorial.model.TaskDao;
import com.example.tutorial.ultils.Constant;

public class OnBootReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		try {
			ReminderManager reminderMgr = new ReminderManager(context);
			DevOpenHelper helper = new DevOpenHelper(context, "task-db", null);
			SQLiteDatabase db = helper.getWritableDatabase();
			DaoMaster daoMaster = new DaoMaster(db);
			DaoSession daoSession = daoMaster.newSession();
			TaskDao taskDao = daoSession.getTaskDao();
			List<Task> taskList = taskDao.loadAll();
			if (taskList != null) {
				Calendar mCalendar = Calendar.getInstance();
				for (Task task : taskList) {
					Calendar mCalTask = Calendar.getInstance();
					mCalTask.setTime(task.getNotifyDate());
					if (!task.getIsCompleted()
							&& mCalendar.getTimeInMillis() <= mCalTask
									.getTimeInMillis()) {
						SimpleDateFormat format = new SimpleDateFormat(
								Constant.DATE_TIME_FORMAT);
						java.util.Date date = format.parse(task.getNotifyDate()
								.toString());
						mCalendar.setTime(date);
						reminderMgr.setReminder(task.getId(), mCalendar);
					}
				}
			}
		} catch (Exception e) {

		}
	}

}
